package webserver

import (
	"encoding/json"
	"gitee.com/zhengjianfeng/pay-tool/common"
	"net"
	"net/http"
	"strconv"
	"time"
)

var (
	// 单例对象
	G_apiServer *ApiServer
)

// 任务的HTTP接口
type ApiServer struct {
	HttpServer *http.Server
}

// 用户下单接口
func handOrderPay(resp http.ResponseWriter, req *http.Request) {

	var (
		err           error
		bytes         []byte
		jsonOrderInfo string
		orderInfo     common.OrderToPay
		merInfo       *common.MerInfo
	)

	// TODO
	if err = req.ParseForm(); err != nil {
		goto ERR
	}

	jsonOrderInfo = req.PostForm.Get("order")

	// 解析json
	if err = json.Unmarshal([]byte(jsonOrderInfo), &orderInfo); err != nil {
		goto ERR
	}

	// 初始化订单类
	if err = InitOrderPay(); err != nil {
		goto ERR
	}

	// 1、验证参数信息
	if err = G_orderPay.CheckOrderParams(orderInfo); err != nil {
		goto ERR
	}

	// 2、查询商户是否存在 现在简单处理默认
	if merInfo, err = common.CheckMerExisted(orderInfo.MerId); err != nil {
		goto ERR
	}

	// 3、验证签名
	if err = common.VerifySign(orderInfo, merInfo.MerSignKey); err != nil {
		goto ERR
	}

	// 4、保存订单
	// todo

	// 5、去上游下单 实际不需要做

	// 正常应答
	if bytes, err = common.BuildResponse(0, "success", nil); err != nil {
		goto ERR
	}

	resp.Write(bytes)
	return

ERR:
	if bytes, err = common.BuildResponse(-1, err.Error(), nil); err == nil {
		resp.Write(bytes)
	}
	return
}

// 初始化事务
func InitApiServer() (err error) {
	// 配置路由
	var (
		mux        *http.ServeMux
		listener   net.Listener
		httpServer *http.Server
		// staticDir     http.Dir     // 静态文件根目录
		// staticHandler http.Handler // 静态文件的HTTP回调
	)

	// 配置路由
	mux = http.NewServeMux()
	mux.HandleFunc("/order/pay", handOrderPay)

	// 静态文件目录
	//staticDir = http.Dir(G_config.WebRoot)
	//staticHandler = http.FileServer(staticDir)
	//mux.Handle("/", http.StripPrefix("/", staticHandler))

	// 启动TCP监听
	if listener, err = net.Listen("tcp", ":"+strconv.Itoa(G_config.ApiPoint)); err != nil {
		return err
	}

	// 启动一个HTTP服务
	httpServer = &http.Server{
		ReadHeaderTimeout: time.Duration(G_config.ApiReadTimeout) * time.Millisecond,
		WriteTimeout:      time.Duration(G_config.ApiWriteTimeout) * time.Millisecond,
		Handler:           mux,
	}

	// 赋值单例
	G_apiServer = &ApiServer{
		HttpServer: httpServer,
	}

	// 启动了服务
	go httpServer.Serve(listener)

	return
}
